const express = require('express');
const cors = require('cors');
const https = require('https');

const app = express();
app.use(cors());
app.use(express.json());

// 请求日志中间件
app.use((req, res, next) => {
    console.log('\n===== 收到请求 =====');
    console.log('时间:', new Date().toISOString());
    console.log('方法:', req.method);
    console.log('路径:', req.path);
    console.log('请求头:', JSON.stringify(req.headers, null, 2));
    console.log('请求体:', JSON.stringify(req.body, null, 2));
    next();
});

// 响应日志中间件
app.use((req, res, next) => {
    const originalSend = res.send;
    res.send = function (body) {
        console.log('\n===== 发送响应 =====');
        console.log('状态码:', res.statusCode);
        console.log('响应体:', body);
        originalSend.call(this, body);
    };
    next();
});

app.use(express.static(__dirname));

app.post('/api/music/generate', async (req, res) => {
    console.log('\n===== 开始处理音乐生成请求 =====');
    const { apiKey, body } = req.body;

    if (!apiKey || !body) {
        console.log('错误: apiKey或body为空');
        return res.status(400).json({ error: 'apiKey和body不能为空' });
    }

    const newBody = {
        model: "ACE-Step-v1-3.5B",
        ...body
    };

    console.log('\n===== 转发到Gitee AI的请求体 =====');
    console.log(JSON.stringify(newBody, null, 2));

    try {
        const response = await fetch("https://ai.gitee.com/v1/async/music/generations", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${apiKey}`
            },
            body: JSON.stringify(newBody)
        });

        console.log('\n===== Gitee AI响应 =====');
        console.log('状态码:', response.status);
        const text = await response.text();
        console.log('原始响应:', text);

        let data;
        try {
            data = JSON.parse(text);
        } catch (parseError) {
            console.log('解析JSON失败:', parseError);
            return res.status(500).json({
                error: `Gitee AI返回非JSON内容（状态码${response.status}）: ${text}`
            });
        }

        res.json(data);
    } catch (e) {
        console.error('请求Gitee AI出错:', e);
        res.status(500).json({ error: e.message });
    }
});

app.post('/download', async (req, res) => {
    if (!(req.body?.url)) {
        res.sendStatus(400);
        return;
    }
    https.get(req.body?.url, (fileres) => {
        res.writeHead(fileres.statusCode, {
            'Content-Type': fileres.headers['content-type'] || 'audio/mpeg',
            'Content-Length': fileres.headers['content-length'],
            'Content-Disposition': 'inline; filename="music.mp3"',
        });

        // 管道转发音频流
        fileres.pipe(res);
    }).on('error', (err) => {
        console.error('远程请求错误:', err.message);
        res.writeHead(500);
        res.end('服务器内部错误');
    });
});
app.listen(3001, () => {
    console.log('Node转发服务已启动，端口3001');
});